<?php
declare (strict_types=1);

namespace app\middleware;


class LogMiddleware {
    /**
     * 记录操作日志
     *
     * @param          $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle($request, \Closure $next) {
        $response = $next($request);
        $ip = $request->ip();
        $method = $request->method();
        $query = $request->all();
        $url = $request->baseUrl();
        $uid = $request->master['uid'] ?? 0;
        $nickname = $request->master['nickname'] ?? '';
        $data = $response->getData();
        $logData = [
            'uid' => $uid,
            'name' => $nickname,
            'method' => $method,
            'url' => $url,
            'query' => http_build_query($query),
            'ip' => $ip,
            'msg' => $data['msg'],
            'code' => $data['code'] ?? 0
        ];
        \think\facade\Log::channel('operation')->write(json_encode($logData, 1), 'operation');
        return $response;
    }
}
